import {Button, Card, Form, message, Modal, Popconfirm, Spin, Table, Upload} from 'antd';
import React, {Component, useState} from 'react';
import {DownloadOutlined, UploadOutlined, WarningOutlined} from "@ant-design/icons";
import styles from "@/pages/Model/model.less";
import {TestDelete, TestList, TestUpload} from "@/services/A10/TestController";
import {ModelList, PredictedData, PredictedMultiData} from "@/services/A10/ModelController";
import {getLoginUserUsingGET} from "@/services/a10_back/userController";

class ExamplePage extends Component{

  state = {
    data: [],
    columns: [],
    loading:false,
    setLoading:false,
    selectedRowKeys:[],
    setSelectedRowKeys:[],
    ModelData:[],
    ModelColumns:[],
    ModelAndTestName: { testName: '', modelName: '',testPath:'',modelPath:'',modelId:'',testId:'',userId:'' },
    showInput:false,
    showInput1:false,
    testId: [],
    ModelColumns1:[],
    currentPage: 1, // 当前页数
    pageSize: 5, // 每页显示条数
    total: 0, // 总条数
  }

  loadData = async () => {
    let user = await getLoginUserUsingGET();
    let userid = user.data.id;
    const data = await TestList(userid);
    const total = data.length;
    this.setState({ data ,total});
  }

  async componentDidMount() {

    let user = await getLoginUserUsingGET();
    let userid = user.data.id;
    const data = await TestList(userid);
    const total = data.length;
    const ModelData = await ModelList(userid);

    const columns = [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        colSpan:0,
        render:()=>{return {props:{colSpan:0}};}
      },
      {
        title: 'url',
        dataIndex: 'url',
        key: 'url',
        colSpan:0,
        render:()=>{return {props:{colSpan:0}};}
      },
      {
        title: '测试文件列表',
        dataIndex: 'fileName',
        key: 'fileName',
      },
      {
        title: '文件大小',
        dataIndex: 'fileSize',
        key: 'fileSize',
      },
      {
        title: '测试',
        dataIndex: 'Download',
        key: 'Download',
        render:(text, record)=> {
          return (<Button type="primary" onClick={() =>this.handleButtonClick(record)} className={styles.ButtonInfo}>选择预测模型</Button>);
        },
      },
      {
        title: '删除',
        key: 'Delete',
        dataIndex: 'Delete',
        render:(text, record)=> {
          return (
            <Popconfirm
              title="确定要删除此文件吗?"
              onConfirm={() => this.handTestDelete(record)}
              icon={
                <WarningOutlined
                  style={{
                    color: 'red',
                  }}
                />
              }
            >
              <Button type="primary" danger className={styles.ButtonInfo} style={{width:'100px'}}>删除文件</Button>
            </Popconfirm>
          );
        },
      }
    ];

    const ModelColumns = [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        colSpan:0,
        render:()=>{return {props:{colSpan:0}};}
      },
      {
        title: 'url',
        dataIndex: 'url',
        key: 'url',
        colSpan:0,
        render:()=>{return {props:{colSpan:0}};}
      },
      {
        title: '已训练模型列表',
        dataIndex: 'fileName',
        key: 'fileName',
        render: (text) => <a>{text}</a>,
      },
      {
        title: '预测',
        key: 'Predicted',
        dataIndex: 'Predicted',
        render:(text, record)=> {
          return (<Button type="primary" onClick={()=>this.handPredictedData(record)} className={styles.ButtonInfo}>预测数据</Button>);
        },
      }
    ];

    const ModelColumns1 = [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
        colSpan:0,
        render:()=>{return {props:{colSpan:0}};}
      },
      {
        title: 'url',
        dataIndex: 'url',
        key: 'url',
        colSpan:0,
        render:()=>{return {props:{colSpan:0}};}
      },
      {
        title: '已训练模型列表',
        dataIndex: 'fileName',
        key: 'fileName',
        render: (text) => <a>{text}</a>,
      },
      {
        title: '预测',
        key: 'Predicted',
        dataIndex: 'Predicted',
        render:(text, record)=> {
          return (<Button type="primary" onClick={()=>this.handPredictedMultiData(record)} className={styles.ButtonInfo}>预测数据</Button>);
        },
      }
    ];

    this.setState({ModelData});
    this.setState({ModelColumns});
    this.setState({ModelColumns1});
    this.setState({columns});
    this.setState({data,total});
  }

  handPredictedMultiData=(record) => {
    const modelId=record.id;
    const startTime = performance.now();
    getLoginUserUsingGET().then(resp => {
      let userid = resp.data.id;
      const requestBody = {
        modelId: modelId,
        userId: userid,
        testIds: this.state.testId
      };
      this.setState({showInput1:false})
      const selectedRowKeys = [];
      this.setState({selectedRowKeys});
      this.setState({ loading: true });
      PredictedMultiData(requestBody).then((resp) => {
        if(resp.data=="success"){
          const endTime = performance.now();
          const executionTime = endTime - startTime;
          const minutes = Math.floor(executionTime / 60000);
          const seconds = Math.floor((executionTime % 60000) / 1000);

          let timeString = "";
          if (minutes > 0) {
            timeString += `${minutes} 分钟 `;
          }
          timeString += `${seconds} 秒`;
          message.success(`数据预测完成,用时${timeString}`);
        }else {
          message.error("模型预测失败");
        }
        this.setState({ loading: false });
      });
    })
  }

  handPredictedData =(record) => {
    const showInput = false;
    this.setState({ loading: true });
    const startTime = performance.now();
    getLoginUserUsingGET().then(resp => {
      let userid= resp.data.id;
      const updatedModelAndTestName =
        { ...this.state.ModelAndTestName, modelName: record.fileName,modelPath: record.url,modelId: record.id,userId: userid };
      this.setState({ showInput, ModelAndTestName: updatedModelAndTestName });
      PredictedData(updatedModelAndTestName).then((resp) => {
        if(resp.data==="success"){
          const endTime = performance.now();
          const executionTime = endTime - startTime;
          const minutes = Math.floor(executionTime / 60000);
          const seconds = Math.floor((executionTime % 60000) / 1000);

          let timeString = "";
          if (minutes > 0) {
            timeString += `${minutes} 分钟 `;
          }
          timeString += `${seconds} 秒`;
          message.success(`数据预测完成,用时${timeString}`);
        }else {
          message.error("模型预测失败");
        }
        this.setState({ loading: false });
      });
    });
  }

  handleButtonClick = (record) => {
    const showInput=true;
    const updatedModelAndTestName =
      { ...this.state.ModelAndTestName, testName: record.fileName,testPath: record.url,testId: record.id };
    this.setState({ showInput, ModelAndTestName: updatedModelAndTestName });
  };

  closeButtonClick = () => {
    const showInput=false;
    const showInput1=false;
    this.setState({showInput,showInput1});
  };

  handUploadTest(formData,fileName){
    const key = 'uploadingMessage';

    // 显示“正在上传”提示
    message.open({
      key,
      type: 'loading',
      content: '文件上传中...',
      duration: 0
    });
    TestUpload(formData).then(
      (resp) => {
        if(resp.data==="success"){
          message.open({
            key,
            type: 'success',
            content: `${fileName} 上传成功`,
            duration: 2,
          });
          this.loadData();
        }else {
          message.open({
            key,
            type: 'error',
            content: `${fileName} 上传失败`,
            duration: 2,
          });
        }

      }
    );
  }

  handTestDelete(record){
    TestDelete(record).then((resp) => {
      if(resp.data==="success"){
        this.loadData();
        message.success("删除文件成功");
      }else {
        message.error("删除文件错误");
      }

    });
  }
  handleUpload = (info) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      const formData = new FormData();
      formData.append('file', info.file.originFileObj, info.file.name); // 将文件数据添加到 formData 对象中
      let userid;
      getLoginUserUsingGET().then(resp => {
        userid = resp.data.id;
        formData.append("userid",userid);
        this.handUploadTest(formData,info.file.name);
      })

    } else if (info.file.status === 'error') {
    }
  }


  start = () => {
    const showInput1=true;
    const testId=this.state.selectedRowKeys;
    this.setState({testId,showInput1});
    console.log(this.state.testId);
  };

  onSelectChange = (newSelectedRowKeys) => {
    this.setState({ selectedRowKeys: newSelectedRowKeys });
  };



  render() {
    const { data ,columns,selectedRowKeys,showInput,
      ModelColumns,ModelData,showInput1,ModelColumns1,currentPage,pageSize,total} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        // 将每行的 name 添加为 checkbox 的 value 值
        value: record.id,
        // 根据数据中的 name 字段判断是否选中
        checked: selectedRowKeys.includes(record.id),
      }),
    };
    const hasSelected = selectedRowKeys.length > 0;
    const pagination = {
      current: currentPage,
      pageSize,
      total,
      onChange: (page) => {
        this.setState({ currentPage: page });
      },
    };
    return (
      <Spin
        size={"large"}
        spinning={this.state.loading}
        tip={<span style={{ color: '#1890ff', fontSize: '18px' }}>数据预测中.....</span>}
        style={{ display: 'flex',alignItems: 'center', marginTop: '50px' }}
      >
      <div>
        <Card>
          <Upload  showUploadList={false} onChange={this.handleUpload} multiple={true}>
            <Button icon={<UploadOutlined />} className={styles.test}  type="primary">上传测试文件</Button>
          </Upload>
          <Button type="primary" onClick={this.start} disabled={!hasSelected} style={{transform: 'translateX(15px) translateY(-12px)',borderRadius:'6px'}}>
            批量预测
          </Button>
          <Table rowSelection={rowSelection} columns={columns} dataSource={data} rowKey="id" pagination={pagination}/>
        </Card>
        <div
          style={{
            marginBottom: 16,
            position: 'relative',
            left: '265px',
            top: '-246px'
          }}
        >
          <span
            style={{
              marginLeft: 8,
            }}
          >
          {hasSelected ? `选择了 ${selectedRowKeys.length} 个文件` : ''}
        </span>
        </div>
        <Modal
          open={showInput}
          cancelText="取消"
          onCancel={() => {this.closeButtonClick();}}
          okButtonProps={{ style: { display: 'none' } }}
        >
          <Form
            layout="vertical"
            name="form_in_modal"
            initialValues={{
              modifier: 'public',
            }}
          >
            <Form.Item>
              <Table columns={ModelColumns} dataSource={ModelData}></Table>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          open={showInput1}
          cancelText="取消"
          onCancel={() => {this.closeButtonClick();}}
          okButtonProps={{ style: { display: 'none' } }}
        >
          <Form
            layout="vertical"
            name="form_in_modal"
            initialValues={{
              modifier: 'public',
            }}
          >
            <Form.Item>
              <Table columns={ModelColumns1} dataSource={ModelData}></Table>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      </Spin>
    );
  }

}

export default ExamplePage;
